ungetc関数は、一度入力したデータを再度入力できるように、ストリームに戻します。戻せるのは1文字だけです。
#include <stdio.h>
int ungetc(int c, FILE *stream);
cはストリームに戻すデータを指定します。
*streamはfopen関数で取得した、ファイルポインタを指定します。
戻り値として、正常に処理できた場合は第1引数のcの値を、エラーの場合はEOFの値を返します。
プログラム 例
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *fp;
int in_data;
int return_code = 0;
if (argc == 2) {
if ((fp = fopen(*(argv+1), 'r')) != NULL) {
while((in_data = fgetc(fp)) != EOF) {
if ((char)in_data == ' ') {
/* スペースだったら、#を戻す */
ungetc('#', fp);
}
else {
/* スペースでなかったら、そのまま出力 */
putchar(in_data);
}
}
fclose(fp);
}
else {
printf('ファイルのオープンに失敗しました\n');
return_code = 1;
}
}
else {
printf('実行時引数の数が不当です\n');
return_code = 2;
}
return return_code;
}
例の実行結果
$ ./ungetc.exe temp.txt
#include#<stdio.h>
int#main()
{
##printf('Hello#World!!.\n');
##return#0;
}
$